/**
 * @function 微信接口调用
 * @description 如果是GET方法 处理url和参数后输出
 */

import { messageFileProps } from 'miniprogram/miniprogram_npm/@vant/weapp/uploader/shared';
import msg from '../msg';
import {Parameter, ParameterExcel} from './interface';
import {getInterfaceRoute} from './route';

function getParamsToUrl(param: Parameter, url: string): string {
  // 判空
  if (param.url.length == 0) {
    return url;
  }
  Object.keys(param.data).forEach((key: string) => {
    url += `&${key}=${param.data[key]}`;
  })
  //console.log('[tools.ts-getParamsToUrl()]', url);
  return url;
}

export async function request(param: Parameter): Promise<WechatMiniprogram.RequestSuccessCallbackResult<string | Record<string, any> | ArrayBuffer>> {
  return new Promise((resolve, reject) => {
    if(param.method == 'GET') {
      param.url = getParamsToUrl(param, getInterfaceRoute(param.url));
      param.data = {};
    }
    wx.request({
      url: param.url,
      method: param.method,
      header: {
        'content-type': 'application/json'
      },
      data: param.data,
      success: (res:any) => {
        if(!res.data.code){
          msg.show('系统维护中','请稍后再试');
        }
        resolve(res);
      },
      fail: err => {
        console.log('发生了错误')
        reject(err);
      }
    })
  })
}
export async function exportExcel(param: ParameterExcel): Promise<WechatMiniprogram.RequestSuccessCallbackResult<string | Record<string, any> | ArrayBuffer>> {
  return new Promise((resolve, reject) => {
    if(param.method == 'GET') {
      param.url = getParamsToUrl(param, getInterfaceRoute(param.url));
      param.data = {};
    }
    wx.request({
      url: param.url, //调用后台接口的全路径
      data: param.data,
      method: param.method,
      header: {
        'Content-type': 'application/x-www-form-urlencoded',
      },
      responseType: 'arraybuffer', //此处是请求文件流，必须带入的属性
      success:(res:any) => {
        //console.log('res=',res);
        if (true){
          const fs = wx.getFileSystemManager(); //获取全局唯一的文件管理器
          fs.writeFile({
            filePath: wx.env.USER_DATA_PATH + "/"+param.fileName+'.xls', // wx.env.USER_DATA_PATH 指定临时文件存入的路径，后面字符串自定义
            data: res.data,
            encoding: "binary", //二进制流文件必须是 binary
            success (res){
              wx.openDocument({ // 打开文档
                filePath: wx.env.USER_DATA_PATH + "/"+param.fileName+'.xls',  //拿上面存入的文件路径
                showMenu: true, // 显示右上角菜单
                success: function (res) {
                  setTimeout(()=>{wx.hideLoading()},500)
                }
              });

            }
          })
        }
      }
    })
  })
}